//
//  YBHomeViewController.m
//  WuyouTang
//
//  Created by YB007 on 2022/5/28.
//  Copyright © 2022 cat. All rights reserved.
//

#import "YBHomeViewController.h"

#import <TYTabPagerBar.h>
#import <TYPagerController.h>
#import "ShopMallVC.h"
#import "myVideoV.h"
#import "MyFollowViewController.h"
#import "searchVC.h"
#import <JMessage/JMessage.h>
#import "YBLiveListVC.h"
#import "YBLookVideoVC.h"
#import "WuyouTangsVC.h"
#import <AFNetworkReachabilityManager.h>
#import <AudioToolbox/AudioToolbox.h>

@interface YBHomeViewController ()<TYTabPagerBarDelegate,TYTabPagerBarDataSource,TYPagerControllerDelegate,TYPagerControllerDataSource,V2TIMConversationListener,V2TIMAdvancedMsgListener>
{
    YBLookVideoVC *_ybLook;
    UIImageView *mask_top;
}
@property(nonatomic,strong)NSArray *baseArray;

@property(nonatomic,strong)TYTabPagerBar *tabBar;
@property(nonatomic,strong)TYPagerController *pagerController;
@property(nonatomic,strong)NSArray *dataArray;

@property(nonatomic,strong)UIButton *search;
@property(nonatomic,strong)UIButton *liveBtn;
@property(nonatomic,strong)NSString *pageTagStr;//0-推荐   1-热门   2-附近  //rk_1-30

@end

@implementation YBHomeViewController

SystemSoundID msgSoundID = 0;

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getUnreadCound];
    // 青少年
    [[YBYoungManager shareInstance] checkYoungStatus:YoungFrom_Home];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //9-27
    [self getUnreadCound];
}
- (void)onTotalUnreadMessageCountChanged:(UInt64)totalUnreadCount {
    [self getUnreadCound];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviView.hidden = YES;
    self.view.backgroundColor = UIColor.whiteColor;
    [Config saveCurrentIsShop:NO];

    TYTabPagerBar *tabBar = [[TYTabPagerBar alloc]init];
    tabBar.dataSource = self;
    tabBar.delegate = self;
    tabBar.layout.barStyle = TYPagerBarStyleProgressView;
    tabBar.layout.selectedTextColor = UIColor.whiteColor;
    tabBar.layout.normalTextColor = UIColor.whiteColor;
    tabBar.layout.selectedTextFont = [UIFont boldSystemFontOfSize:18];
    tabBar.layout.normalTextFont = [UIFont boldSystemFontOfSize:18];
    tabBar.layout.progressColor = UIColor.whiteColor;
    tabBar.layout.progressHeight = 4;
    tabBar.layout.progressRadius = 2;
    tabBar.layout.progressHorEdging = 10;
    tabBar.layout.progressVerEdging = 5;
    tabBar.layout.cellWidth = 0;
    tabBar.layout.cellSpacing = 0;
    tabBar.backgroundColor = UIColor.clearColor;
    
    [tabBar registerClass:[TYTabPagerBarCell class] forCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier]];
    [self.view addSubview:tabBar];
    _tabBar = tabBar;
    TYPagerController *pagerController = [[TYPagerController alloc] init];
    pagerController.dataSource = self;
    pagerController.delegate = self;
    pagerController.layout.adjustScrollViewInset = NO;
    [self addChildViewController:pagerController];
    [self.view addSubview:pagerController.view];
    _pagerController = pagerController;
    
    mask_top = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _window_width, 100+statusbarHeight)];
    [mask_top setImage:[UIImage imageNamed:@"home_mask_top"]];
    [self.view addSubview:mask_top];
    
    UIImageView* mask_buttom = [[UIImageView alloc] initWithFrame:CGRectMake(0,  _window_height-49-ShowDiff-44, _window_width, 49)];
    [mask_buttom setImage:[UIImage imageNamed:@"home_mask_bottom"]];
    mask_buttom.userInteractionEnabled = YES;
    [self.view addSubview:mask_buttom];
    
    [self.view bringSubviewToFront:tabBar];
    [self.view addSubview:self.search];
    [self.view addSubview:self.liveBtn];
    [self registVoice];
    [self infoSet:NO];
    [self netMonitoring];
    //获取未读消息
    [[V2TIMManager sharedInstance] addConversationListener:self];
    [[V2TIMManager sharedInstance]addAdvancedMsgListener:self];
    //rk_1-30
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doubleClickRefresh) name:DoubleClickRefreshNot object:nil];
    //rk_net
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needRefreshPage) name:@"FirstGetVideoClass" object:nil];
    //邀请码
    [YBInviteCode checkAgent];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needRefreshPage) name:@"topTabbarScrolUnEnable" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needRefreshPage) name:@"topTabbarScrolEnable" object:nil];
    
    // 直播入口
    [BGSetting getBgSettingUpdate:NO maintain:NO eventBack:^(id event) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([PublicObj isUp]) {
                _liveBtn.hidden = YES;
            }else {
                _liveBtn.hidden = NO;
            }
        });
    }];
}
-(void)topTabbarScrolUnEnable{
    _tabBar.userInteractionEnabled =NO;
    _pagerController.scrollView.scrollEnabled = NO;
}
-(void)topTabbarScrolEnable{
    _tabBar.userInteractionEnabled =YES;
    _pagerController.scrollView.scrollEnabled = YES;

}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    _tabBar.frame = CGRectMake(50, statusbarHeight+20, _window_width-105, 44);
    _pagerController.view.frame = CGRectMake(0, 0, _window_width, _window_height-49-ShowDiff);
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)doubleClickRefresh {
    //是首页并且是推荐才执行双击刷新
    if ([_pageTagStr isEqual:@"0"]) {
        [_ybLook doubleClickRefreshForYou];
    }
}
//rk_net
-(void)needRefreshPage {
    [self infoSet:YES];
}
//rk_net
-(void)infoSet:(BOOL)refresh {
    NSArray *videoClass = [NSArray arrayWithArray:[common getVideoClass]];
    _baseArray = [NSArray arrayWithObjects:YZMsg(@"搜索"),YZMsg(@"关注"),YZMsg(@"商城"),nil];
    NSMutableArray *m_array = [NSMutableArray array];
    [m_array addObjectsFromArray:_baseArray];
    for (NSDictionary *classDic in videoClass) {
        NSString *title = minstr([classDic valueForKey:@"title"]);
        [m_array addObject:title];
    }
    //反转
    NSArray *reverseArray = [[m_array reverseObjectEnumerator] allObjects];
    self.dataArray = [NSArray arrayWithArray:reverseArray];
    if (refresh && videoClass.count > 0) {
        //第一安装由于网络权限问题顶部分类未显示,这里收到通知刷新
        [[AFNetworkReachabilityManager sharedManager]stopMonitoring];
        [_tabBar reloadData];
        [_pagerController updateData];
    }else{
        [_tabBar reloadData];
        [_pagerController reloadData];
    }
   
    [_pagerController scrollToControllerAtIndex:(_dataArray.count-1) animate:NO];
}
-(UIButton *)search {
    if (!_search) {
        _search = [UIButton buttonWithType:0];
        [_search setImage:[UIImage imageNamed:@"home_search"] forState:0];
        _search.frame = CGRectMake(10, 20+statusbarHeight, 40, 40);
        [_search addTarget:self action:@selector(doSearchBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _search;
}
- (UIButton *)liveBtn {
    if (!_liveBtn) {
        _liveBtn = [UIButton buttonWithType:0];
        [_liveBtn setImage:[UIImage imageNamed:@"直播广场"] forState:0];
        _liveBtn.frame = CGRectMake(_window_width-50, 20+statusbarHeight, 40, 40);
        [_liveBtn addTarget:self action:@selector(doLiveBtn) forControlEvents:UIControlEventTouchUpInside];
        _liveBtn.hidden = YES;
    }
    return _liveBtn;
}
#pragma mark - 点击事件
-(void)doSearchBtn {
//    if ([[Config getOwnID] intValue]<=0 && [Config getTranslate]) {
//        return;
//    }
    searchVC *search = [[searchVC alloc]init];
    search.searchFrom = SearchFrom_Home;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:search animated:YES];
}
-(void)doLiveBtn {
//    if ([[Config getOwnID] intValue]<=0 && [Config getTranslate]) {
//        return;
//    }
    YBLiveListVC *lVC = [[YBLiveListVC alloc]init];
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:lVC animated:YES];
}
-(void)scrollToIdx:(int)idx refresh:(BOOL)refresh{
//    [_pagerController scrollToControllerAtIndex:idx animate:NO];
    // 推荐
    [_pagerController scrollToControllerAtIndex:(_dataArray.count-1) animate:NO];
    if (refresh) {
        [_ybLook youngModeRefresh];
    }
}
#pragma mark - TYTabPagerBarDataSource
- (NSInteger)numberOfItemsInPagerTabBar {
    return _dataArray.count;
}
- (UICollectionViewCell<TYTabPagerBarCellProtocol> *)pagerTabBar:(TYTabPagerBar *)pagerTabBar cellForItemAtIndex:(NSInteger)index {
    UICollectionViewCell<TYTabPagerBarCellProtocol> *cell = [pagerTabBar dequeueReusableCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier] forIndex:index];
    cell.titleLabel.text = _dataArray[index];
    return cell;
}

#pragma mark - TYTabPagerBarDelegate
- (CGFloat)pagerTabBar:(TYTabPagerBar *)pagerTabBar widthForItemAtIndex:(NSInteger)index {
    NSString *title = _dataArray[index];
    return [pagerTabBar cellWidthForTitle:title];
}

- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar didSelectItemAtIndex:(NSInteger)index {
    [_pagerController scrollToControllerAtIndex:index animate:YES];
    // index == 3
    if((index+4) == _dataArray.count){
        mask_top.hidden = YES;
        _tabBar.layout.selectedTextColor = UIColor.blackColor;
        _tabBar.layout.normalTextColor = UIColor.grayColor;
        _tabBar.layout.progressColor = UIColor.blackColor;
        [_search setImage:[UIImage imageNamed:@"home_search_black"] forState:0];
        [_liveBtn setImage:[UIImage imageNamed:@"直播广场_black"] forState:0];

        [Config saveCurrentIsShop:YES];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changTabBarColor" object:@"1"];
//        });

    }else{
        mask_top.hidden = NO;
        _tabBar.layout.selectedTextColor = UIColor.whiteColor;
        _tabBar.layout.normalTextColor = UIColor.whiteColor;
        _tabBar.layout.progressColor = UIColor.whiteColor;
        [_search setImage:[UIImage imageNamed:@"home_search"] forState:0];
        [_liveBtn setImage:[UIImage imageNamed:@"直播广场"] forState:0];

        [Config saveCurrentIsShop:NO];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changTabBarColor" object:@"0"];
//        });

    }
    [_tabBar reloadData];
}

#pragma mark - TYPagerControllerDataSource
- (NSInteger)numberOfControllersInPagerController {
    return _dataArray.count;
}

-(void)lookVideoPanLeft {
    [_pagerController scrollToControllerAtIndex:_dataArray.count-2 animate:YES];
}

- (UIViewController *)pagerController:(TYPagerController *)pagerController controllerForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
    
    _pageTagStr = [NSString stringWithFormat:@"%ld",index];
   if((index+1) == _dataArray.count){
       _pageTagStr = @"0";
       _ybLook = [[YBLookVideoVC alloc]init];
       _ybLook.isForyou = YES;
       YBWeakSelf;
       _ybLook.leftEvent = ^{
           [weakSelf lookVideoPanLeft];
       };
//        _ybLook.sourceBaseUrl = [NSString stringWithFormat:@"Video.getRecommendVideos&uid=%@",[Config getOwnID]];
       _ybLook.sourceBaseUrl = [NSString stringWithFormat:@"Video.getRecommendVideos&uid=%@&mobileid=%@",[Config getOwnID],[PublicObj getDeviceUUID]];

       _ybLook.scrollViewDirection = ZFPlayerScrollViewDirectionVertical;
       return _ybLook;
   } else if((index+2) == _dataArray.count) {
       _pageTagStr = @"1";
       myVideoV *videoVC= [[myVideoV alloc]init];
       NSString *url = [NSString stringWithFormat:@"Video.getVideoList&uid=%@&type=0",[Config getOwnID]];
       videoVC.url = url;

       videoVC.view.frame = CGRectMake(0,64+statusbarHeight, _window_width, _window_height-64-statusbarHeight-49-ShowDiff);
       videoVC.ismyvideo = 0;
       
       return videoVC;
   }else if((index+3) == _dataArray.count) {
       _pageTagStr = @"2";
       /*
       NearbyVC *videoVC= [[NearbyVC alloc]init];
       NSString *url = [NSString stringWithFormat:@"Video.getNearby&uid=%@&lng=%@&lat=%@",[Config getOwnID],[cityDefault getLocationLng],[cityDefault getLocationLat]];
       videoVC.url = url;
       return videoVC;
        */
       MyFollowViewController *videoVC = [[MyFollowViewController alloc]init];
       videoVC.url = @"video.getAttentionVideo";
       return videoVC;
   }else if((index+4) == _dataArray.count) {
       ShopMallVC *shopmall = [[ShopMallVC alloc]init];
       return shopmall;
   }else{
       int showIndex = (int)index - (int)_baseArray.count;
       if (showIndex < 0 ) {
           showIndex = 0;
       }
       NSDictionary *subDic = @{};
       if ([common getVideoClass].count > showIndex) {
           subDic = [common getVideoClass][showIndex];
       }
       WuyouTangsVC *classVC = [[WuyouTangsVC alloc]init];
       classVC.classID = minstr([subDic valueForKey:@"id"]);
       return classVC;
   }
}
#pragma mark - TYPagerControllerDelegate
- (void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated {
//    if ([[Config getOwnID] intValue]<=0 && [Config getTranslate]) {
//        [_pagerController scrollToControllerAtIndex:0 animate:NO];
//        return;
//    }
    NSLog(@"TOIDNEX======:%ld",toIndex);
    [_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex animate:animated];
    //toIndex == 3
    if((toIndex+4) == _dataArray.count){
        mask_top.hidden = YES;
        [Config saveCurrentIsShop:YES];

        _tabBar.layout.selectedTextColor = UIColor.blackColor;
        _tabBar.layout.normalTextColor = UIColor.grayColor;
        _tabBar.layout.progressColor = UIColor.blackColor;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changTabBarColor" object:@"1"];
//        });
        [_search setImage:[UIImage imageNamed:@"home_search_black"] forState:0];
        [_liveBtn setImage:[UIImage imageNamed:@"直播广场_black"] forState:0];

    }else{
        mask_top.hidden = NO;
        [Config saveCurrentIsShop:NO];

        _tabBar.layout.selectedTextColor = UIColor.whiteColor;
        _tabBar.layout.normalTextColor = UIColor.whiteColor;
        _tabBar.layout.progressColor = UIColor.whiteColor;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changTabBarColor" object:@"0"];
//        });
        [_search setImage:[UIImage imageNamed:@"home_search"] forState:0];
        [_liveBtn setImage:[UIImage imageNamed:@"直播广场"] forState:0];

    }
    [_tabBar reloadData];

}

-(void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
//    if ([[Config getOwnID] intValue]<=0 && [Config getTranslate]) {
//        [_pagerController scrollToControllerAtIndex:0 animate:NO];
//        return;
//    }
    NSLog(@"transitionFromIndex======:%ld",toIndex);
    
    [_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex progress:progress];
//    NSInteger realIndex = progress>0.5?toIndex:fromIndex;

}

#pragma mark - tab 加提示数量 start
-(void)getUnreadCound {
    __block NSInteger  unRead = 0;
    [[YBImManager shareInstance]getAllUnredNumExceptUser:@[@"dsp_user_"] complete:^(int allUnread) {
        unRead = allUnread;
        dispatch_async(dispatch_get_main_queue(), ^{
            [PublicObj setTabbarBadgeValue:(int)unRead];
        });

    }];
    
}
-(void)onRecvNewMessage:(V2TIMMessage *)msg
{
    NSString *fromeName = minstr(msg.sender);
//    if ([PublicObj checkNull:fromeName]) {
//        fromeName = minstr(msg.fromUser.username);
//    }
//    //2020-12-17调整为用户私信不提示
//    if ([fromeName containsString:@"dsp_admin_1"] ||
//        [fromeName containsString:@"dsp_admin_2"] ||
//        [fromeName containsString:@"dsp_fans"] ||
//        [fromeName containsString:@"dsp_like"] ||
//        [fromeName containsString:@"dsp_at"] ||
//        [fromeName containsString:@"dsp_comment"]||
//        [fromeName containsString:@"goodsorder_admin"]
//        ) {
        [self playVoice];
//    }

}
-(void)onReceiveMessage:(JMSGMessage *)message error:(NSError *)error{
    [self getUnreadCound];
    
    NSString *fromeName = minstr(message.fromName);
    if ([PublicObj checkNull:fromeName]) {
        fromeName = minstr(message.fromUser.username);
    }
    
    //2020-12-17调整为用户私信不提示
    if ([fromeName containsString:@"dsp_admin_1"] ||
        [fromeName containsString:@"dsp_admin_2"] ||
        [fromeName containsString:@"dsp_fans"] ||
        [fromeName containsString:@"dsp_like"] ||
        [fromeName containsString:@"dsp_at"] ||
        [fromeName containsString:@"dsp_comment"]||
        [fromeName containsString:@"goodsorder_admin"]
        ) {
        [self playVoice];
    }
    
}
-(void)registVoice {
//    NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"messageVioce" withExtension:@"mp3"];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"messageVioce" ofType:@"mp3"];
    if (path) {
        NSURL *soundUrl = [NSURL fileURLWithPath:path];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundUrl,&msgSoundID);
    }
    
}
- (void)playVoice{
    //个中-设置开关，打开才播放
    if (![common getMsgVoiceSwitch]) {
        return;
    }
    AudioServicesPlaySystemSound(msgSoundID);
}
- (void)onReceiveMessageRetractEvent:(JMSGMessageRetractEvent *)retractEvent;{
    [self getUnreadCound];
}

-(void)netMonitoring {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                break;
            case AFNetworkReachabilityStatusNotReachable:
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [WYNetworking getVideoClass:YES];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [WYNetworking getVideoClass:YES];
                break;
            default:
                break;
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

@end
